package com.jzo2o.customer.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IBankAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 银行账户 服务实现类
 * </p>
 *
 * @author loe
 * @since 2024-08-14
 */
@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements IBankAccountService {

    @Override
    @Transactional
    public BankAccountResDTO saveOrUpdateAccount(BankAccountUpsertReqDTO upsertReqDTO) {
        BankAccount entity = BeanUtil.toBean(upsertReqDTO, BankAccount.class);
        BankAccount bankAccount = baseMapper.selectById(upsertReqDTO.getId());
        if (ObjectUtil.isNull(bankAccount)) {
            entity.setCreateTime(LocalDateTime.now());
            entity.setUpdateTime(LocalDateTime.now());
            save(entity);
        } else {
            entity.setUpdateTime(LocalDateTime.now());
            baseMapper.updateById(entity);
        }
        return BeanUtil.toBean(baseMapper.selectById(entity.getId()), BankAccountResDTO.class);
    }

    @Override
    public BankAccountResDTO currentUserBankAccount(Long id) {
        if (id == null) {
            throw new BadRequestException("查询账户失败");
        }
        return BeanUtil.toBean(baseMapper.selectById(id), BankAccountResDTO.class);
    }
}
